<?php
/**
 * Class UserPlat
 * Desc
 * Create on 2021/10/15 16:16
 * Create by wangyafang
 */

namespace app\api\controller\xyb;

use app\common\model\xyb\UserBelong;
use addons\xyb\library\WXBizDataCrypt;
use app\api\model\xyb\UserPlat as UserPlatModel;
use app\api\model\xyb\UserWechat;

class UserPlat extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * desc:获取微信用户手机号信息
     */
    public function get_wechat_mobile()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();

        $appid = $this->configObj->app_id;
        $user_id = $this->auth->id;

        $sessionKey = (new UserBelong())->where('user_id',$user_id)->value('session_key');
        if(isset($param['code']) && !empty($param['code'])) {
            $wxResult = (new User())->get_wechat_session($param['code']);
            $sessionKey = $wxResult['session_key'];
            (new UserBelong())->where([
                'user_id'=>$user_id,
            ])->update([
                'session_key'=>$sessionKey,
            ]);
        }

        $obj = new  WXBizDataCrypt($appid,$sessionKey);
        $encryptedData=$param['encryptedData'];

        $iv = $param['iv'];
        $errCode = $obj->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $json_data = json_decode($data,true);
            $userPlatObj = (new UserPlatModel())->where('user_id',$this->auth->id)->find();
            if($userPlatObj) {
                (new UserPlatModel())->where([
                    'user_id'=>$user_id,
                ])->update([
                    'mobile'=>$json_data['phoneNumber'],
                ]);
            } else {
                $openid = (new UserBelong())->where('user_id',$user_id)->value('openid');
                if(!$openid) {
                    $this->error('获取手机号失败');
                }
                $wechat_id = (new UserWechat())->where('openid',$openid)->value('id');
                if(!$wechat_id) {
                    $this->error('绑定手机号失败');
                }
                UserPlatModel::create([
                    'user_id'=>$user_id,
                    'mobile'=>$json_data['phoneNumber'],
                    'wechat_id'=>$wechat_id,
                ]);
            }
            $this->success('获取手机号成功',['mobile'=>$json_data['phoneNumber']]);
        } else {
            $this->error($errCode);
        }

    }
}